from datetime import datetime
from enum import Enum
from typing import Dict, Any


class Priority(Enum):
    """任务优先级枚举"""
    LOW = "低"
    MEDIUM = "中"
    HIGH = "高"


class TaskStatus(Enum):
    """任务状态枚举"""
    PENDING = "待完成"
    COMPLETED = "已完成"


class Task:
    """任务数据模型"""
    
    def __init__(self, title: str, description: str = "", priority: Priority = Priority.MEDIUM):
        self.id = self._generate_id()
        self.title = title
        self.description = description
        self.priority = priority
        self.status = TaskStatus.PENDING
        self.created_at = datetime.now()
        self.updated_at = datetime.now()
        self.completed_at = None
    
    def _generate_id(self) -> str:
        """生成唯一ID"""
        return str(int(datetime.now().timestamp() * 1000000))
    
    def mark_completed(self):
        """标记任务为已完成"""
        self.status = TaskStatus.COMPLETED
        self.completed_at = datetime.now()
        self.updated_at = datetime.now()
    
    def mark_pending(self):
        """标记任务为待完成"""
        self.status = TaskStatus.PENDING
        self.completed_at = None
        self.updated_at = datetime.now()
    
    def update(self, title: str = None, description: str = None, priority: Priority = None):
        """更新任务信息"""
        if title is not None:
            self.title = title
        if description is not None:
            self.description = description
        if priority is not None:
            self.priority = priority
        self.updated_at = datetime.now()
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'priority': self.priority.value,
            'status': self.status.value,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'completed_at': self.completed_at.isoformat() if self.completed_at else None
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Task':
        """从字典创建任务对象"""
        task = cls(data['title'], data['description'])
        task.id = data['id']
        task.priority = Priority(data['priority'])
        task.status = TaskStatus(data['status'])
        task.created_at = datetime.fromisoformat(data['created_at'])
        task.updated_at = datetime.fromisoformat(data['updated_at'])
        if data['completed_at']:
            task.completed_at = datetime.fromisoformat(data['completed_at'])
        return task
    
    def __str__(self) -> str:
        return f"Task(id={self.id}, title='{self.title}', status={self.status.value})"